import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/auth.config';

export async function POST(request: Request) {
  try {
    const session = await getServerSession(authOptions);
    
    // 添加详细的日志
    console.log('Session:', session);
    console.log('User ID:', session?.user?.id);
    
    if (!session?.user?.id) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    // 首先验证用户是否存在
    const user = await prisma.user.findUnique({
      where: { id: session.user.id }
    });

    if (!user) {
      return NextResponse.json({ error: '用户不存在' }, { status: 404 });
    }

    const body = await request.json();
    const { name, description, imageUrl, metadata, activities } = body;

    // 创建目的地
    const destination = await prisma.destination.create({
      data: {
        name,
        description,
        imageUrl,
        metadata,
        createdById: user.id,
        isOfficial: false,
      },
      include: {
        _count: {
          select: {
            activities: true
          }
        },
        savedBy: true
      }
    });

    return NextResponse.json(destination);
  } catch (error: any) {
    // 添加更详细的错误日志
    console.error('Create destination error:', {
      error,
      message: error.message,
      code: error.code,
      meta: error.meta,
    });
    
    return NextResponse.json(
      { error: '创建目的地失败', details: error.message },
      { status: 500 }
    );
  }
}

export async function GET() {
  try {
    const destinations = await prisma.destination.findMany({
      where: {
        isOfficial: true
      },
      include: {
        savedBy: {
          select: {
            id: true,
            name: true
          }
        },
        _count: {
          select: {
            activities: true
          }
        }
      }
    });

    return NextResponse.json(destinations);
  } catch (error) {
    console.error('Get destinations error:', error);
    return new NextResponse('Internal error', { status: 500 });
  }
} 